
const express = require('express');
const router = express.Router();
const SurgicalTreatmentModel = require('../db/SurgicalTreatmentModel');
const PatientModel = require('../db/PatientModel');//患者模型
const OrderModel = require('../db/OrderModel');//订单模型
const Medicalinfor = require('../db/MedicalinforMation');//就诊信息模型
const RegistrationinformationModel = require('../db/RegistrationinforMation');//挂号接诊信息
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
};
const UserModel = require('../db/UserModel');//用户模型
const DepartmentModel = require('../db/DepartmentModel');
const CmmuseumModel = require('../db/CmmuseumModel');//门店表
/**
 * 外科治疗模版crud
 * 
 */

router.get('/save', (req, res) => {
    if (req.query.name == '' || req.query.department == '') {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    const temp = new SurgicalTreatmentModel(req.query);
    temp.save().then(() => {
        return res.json({
            code: 200,
            mes: '模版增加成功。'
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '模版增加失败。'
        });
    })
});

router.get('/remove', (req, res) => {
    const id = req.query.id;
    SurgicalTreatmentModel.remove({ _id: id }).then(docs => {
        return res.json({
            code: 200,
            mes: '删除成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '删除失败。'
        });
    })
});

router.post('/update', (req, res) => {
    const id = req.body.id;
    const temp = req.body;
    if (id == '') {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    SurgicalTreatmentModel.update({ _id: id }, {
        $set: temp
    }).then(docs => {
        return res.json({
            code: 200,
            mes: '修改成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '修改失败。'
        });
    })
});

router.get('/find', (req, res) => {
    SurgicalTreatmentModel.find().then(docs => {
        return res.json({
            code: 200,
            mes: '查询成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '查询失败。'
        });
    })
});

router.get('/findone', (req, res) => {
    const id = req.query.id;
    SurgicalTreatmentModel.findOne({ _id: id }).then(docs => {
        return res.json({
            code: 200,
            mes: '查询成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '查询失败。'
        });
    })
});

//外科治疗-接诊列表
router.post('/list', function (req, res) {
    let searchtext = req.body.searchtext;
    let starttime = req.body.starttime
    let endtime = req.body.endtime;
    let doctor_id = req.body.doctor_id;
    let status = req.body.status;
    let pageindex = req.body.pageindex || 1;//页码
    let pagesize = req.body.pagesize || 12;//每页显示数据条数  createtime: { $gte: starttime }, createtime: { $lte: endtime } 
    let query = { "doctor.id": doctor_id };

    if (!doctor_id) {
        return res.json({
            code: 201,
            mes: '缺少必要参数.'
        });
    }
    if (status == 2 || status == 3) {//待接诊或接诊中
        if (starttime && endtime) {
            query.receptiontime = { $gte: moment(new Date(starttime).getTime()).format('YYYY-MM-DD 00:00:00'), $lte: moment(new Date(endtime).getTime()).format('YYYY-MM-DD 24:00:00') };//字符串转格式化日期
            query.paystate = 2;
        } else {
            query.receptiontime = { $gte: moment().format('YYYY-MM-DD 00:00:00'), $lte: moment().format('YYYY-MM-DD 24:00:00') };
            query.paystate = 2;
        }
        query.$or = [{ receptionstate: 2 }, { receptionstate: 3 }];
    } else if (status == 4) {//已完成
        if (starttime && endtime) {
            query.receptiontime = { $gte: moment(new Date(starttime).getTime()).format('YYYY-MM-DD 00:00:00'), $lte: moment(new Date(endtime).getTime()).format('YYYY-MM-DD 24:00:00') };//字符串转格式化日期
        }
        query.receptionstate = status;
        //query['cureorder.state'] = 2;
    }
    if (starttime || endtime) {
        query.receptiontime = { $gte: starttime + " 00:00:00", $lte: endtime + " 24:00:00" };
    };

    if (searchtext) {
        const reg = new RegExp(searchtext, 'i');
        PatientModel.find({ $or: [{ username: { $regex: reg } }, { userphone: { $regex: reg } }] }, ['_id']).then(pt => {
            let ptarr = [];
            for (let i = 0; i < pt.length; i++) {
                ptarr.push(pt[i].id);
            }
            query.payer = { $in: ptarr };
            RegistrationinformationModel.count(query).then(counts => {
                RegistrationinformationModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(docs => {
                    let patientarr = [];
                    let orderarr = [];
                    for (let i = 0; i < docs.length; i++) {
                        patientarr.push(docs[i].payer);
                        orderarr.push(docs[i].orderid);
                    }
                    let patientobj = {};
                    return Promise.all([PatientModel.find({ _id: { $in: patientarr } })]).then(pmes => {
                        for (let i = 0; i < pmes[0].length; i++) {
                            patientobj[pmes[0][i]._id] = pmes[0][i];
                        }
                        for (let i = 0; i < docs.length; i++) {
                            docs[i].patient = patientobj[docs[i].payer];
                        }
                        return res.json({
                            code: 200,
                            mes: '查询成功。',
                            data: docs,
                            count: counts
                        });
                    });
                }).catch(err => {
                    return res.json({
                        code: 201,
                        mes: '查询失败。'
                    });
                })
            })
        })
    } else {
        RegistrationinformationModel.count(query).then(counts => {
            RegistrationinformationModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(docs => {
                let patientarr = [];
                let orderarr = [];
                for (let i = 0; i < docs.length; i++) {
                    patientarr.push(docs[i].payer);
                    orderarr.push(docs[i].orderid);
                }
                let patientobj = {};
                return Promise.all([PatientModel.find({ _id: { $in: patientarr } })]).then(pmes => {
                    for (let i = 0; i < pmes[0].length; i++) {
                        patientobj[pmes[0][i]._id] = pmes[0][i];
                    }
                    for (let i = 0; i < docs.length; i++) {
                        docs[i].patient = patientobj[docs[i].payer];
                    }
                    return res.json({
                        code: 200,
                        mes: '查询成功。',
                        data: docs,
                        count: counts
                    });
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        })
    }

});
//外科治疗保存医生接诊信息
router.post("/treatmentInformation", (req, res) => {
    let _id = req.body.id;
    let doctorid = req.body.doctorid;
    let doctorname = req.body.doctorname;
    let department = req.body.department;
    let clinicname = req.body.clinicname;
    try {
        var { seedoctortime, action,
            nowmedical, historymedical,
            irritability, personage, family,
            tentative, treatmentoptions } = JSON.parse(req.body.data);
    } catch (error) {
        return res.json({
            code: 201,
            mes: '参数格式错误.'
        });
    }
    if (!seedoctortime || !action || !_id || !irritability || !doctorid || !doctorname) {
        return res.json({
            code: 201,
            mes: '缺少必要参数.'
        });
    }
    let info = JSON.parse(req.body.data);
    info.id = _id;
    info.doctorid = doctorid;
    info.doctorname = doctorname;
    info.department = department;
    info.clinicname = clinicname;
    info.savetime = moment().format('YYYY-MM-DD HH:mm:')
    let id = _id;
    if (!id) {
        return res.json({
            code: 201,
            mes: "缺少必要参数"
        })
    }
    Medicalinfor.findOne({ id: id, seedoctortime: seedoctortime }).then(data => {
        if (data) {
            return Medicalinfor.update({ _id: data._id, seedoctortime: seedoctortime }, { $set: info }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.',
                    data: data._id
                });
            })
        } else {
            return Medicalinfor.create(info).then(data => {
                return res.json({
                    code: 200,
                    mes: '保存成功.',
                    data: data._id
                });
            })
        }
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "发生错误",
            err
        })
    });
});

//完成就诊
router.post("/complete", (req, res) => {
    const _id = req.body.patient_id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, { $set: { status: 4 } }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '修改失败.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});

//外科治疗保存用药/用量：
router.post("/saveDrug", (req, res) => {
    let _id = req.body.patient_id;
    try {
        var dataArr = JSON.parse(req.body.data);
    } catch (error) {
        return res.json({
            code: 201,
            mes: '参数格式错误.'
        });
    }
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少必要参数."
        })
    }
    return PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, {
                $push: {
                    docMedicinal: {
                        $each: dataArr
                        // $slice: -4 截取
                    }
                },
            }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});

//费用预览
router.use("/previewFee", (req, res) => {
    let _id = req.body.patient_id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: '缺少参数.'
        });
    }
    return PatientModel.findOne({ _id }, { docMedicinal: 1, membertypes: 1 }).then(data => {
        let amount = 0; //金额合计:
        let discount = 0;  //折扣金额:
        let receivableAmount = 0;//应收金额:
        let paidinAmount = 0;  //实收金额:
        for (let a = 0; a < data.docMedicinal.length; a++) {
            discount += data.docMedicinal[a].totalPrice - data.docMedicinal[a].discountMoney * 1;
            amount += data.docMedicinal[a].totalPrice * 1;
            receivableAmount += data.docMedicinal[a].discountMoney * 1;
            paidinAmount += data.docMedicinal[a].discountMoney * 1;
        }
        return res.json({
            code: 200,
            data,
            amount,
            discount,
            receivableAmount,
            paidinAmount,
            mes: '查询成功.'
        });
    }).catch(err => {
        return res.json({
            code: 203,
            err,
            mes: '查询成功错误,请稍后重试.'
        });
    })
});
//外科治疗修改用药/用量：
router.post("/editorDrug", (req, res) => {
    let _id = req.body.patient_id;
    try {
        var dataArr = JSON.parse(req.body.data);
    } catch (error) {
        return res.json({
            code: 201,
            mes: '参数格式错误.'
        });
    }
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少必要参数."
        })
    }
    return PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, {
                $set: {
                    docMedicinal: dataArr
                },
            }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});
//外科治疗订单列表详情
router.use("/particulars", (req, res) => {
    let patient_id = req.body.patient_id;
    let starttime = req.body.starttime;
    let endtime = req.body.endtime;
    let pageindex = req.body.pageindex || 1;//页码
    let pagesize = req.body.pagesize || 10;//每页显示数据条数
    let query = { payer: patient_id, ordertype: { $regex: "接诊费" } };
    if (starttime || endtime) {
        query.consumptiontime = { $gte: starttime + " 00:00", $lte: endtime + " 24:00" }
        //delete query["payer"];
    };
    if (!patient_id) {
        return res.json({
            code: 201,
            mes: "缺少参数."
        })
    }
    // query.paystate = 2;
    let count;
    return OrderModel.count(query).then(counts => {
        count = counts
        return OrderModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(data => {
            return Promise.all(data.map(values => {
                return DepartmentModel.find({ _id: values.department }).then(name => {
                    values.department = name[0].name;
                    return values;
                })
            }))
        })
    }).then(data => {
        return res.json({
            data,
            count,
            code: 200,
            mes: "查询成功."
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "查询失败",
            err
        })
    })
});
//外科治疗订单列表详情-订单服务项目修改
router.use("/modification", (req, res) => {
    let orderid = req.body.order_id;
    let index = parseInt(req.body.index);
    let datas;
    try {
        datas = JSON.parse(req.body.data)
    } catch (error) {
        return res.json({
            code: 201,
            mes: "参数格式错误.",
            error
        })
    }
    if (!orderid) {
        return res.json({
            code: 201,
            mes: "缺少必要参数"
        })
    }
    let update_date = {};
    for (let ab in datas) {
        update_date[`chargeschedule.${index}.${ab}`] = datas[ab];
    }
    // update_date.$inc = { "chargeschedule.0.p_servedNumber": 1 }
    return OrderModel.update({ orderid }, { $set: update_date }).then(data => {
        return res.json({
            code: 200,
            mes: "修改成功",
            data
        })
    }).catch(err => {
        console.log(err)
        return res.json({
            code: 201,
            mes: "查询失败",
            err
        })
    })
});
//外科治疗查看患者诊疗信息
router.get("/treatmentlook/:id", (req, res) => {
    let id = req.params.id;
    let pageindex = req.params.pageindex || 1;//页码
    let pagesize = req.params.pagesize || 10;//每页显示数据条数
    if (!id) {
        return res.json({
            code: 201,
            mes: '缺少必要参数.'
        });
    };
    // let data;
    Medicalinfor.count({ id: id }).then(consts => {
        return Medicalinfor.find({ id: id }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(data => {
            return Promise.all(data.map(values => {
                return DepartmentModel.find({ _id: values.department }).then(name => {
                    values.department = name.length > 0 ? name[0].name : null;
                    return values;
                })
            }))
        })
    }).then(data => {
        return Promise.all(data.map(values => {
            return CmmuseumModel.find({ _id: values.clinicname }, { name: 1 }).then(name => {
                values.clinicname = name.length > 0 ? name[0].name : null;
                return values
            })
        }));
    }).then(values => {
        return Promise.all(values.map(data => {
            return OrderModel.find({ Medicali_id: data._id, $or: [{ paystate: 2 }, { paystate: 3 }] }).then(datas => {
                data._doc.Order = datas.length > 0 ? datas : null;
                return data
            })
        }))
    }).then(data => {
        return res.json({
            code: 200,
            mes: '查询成功.',
            data
        });
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '数据库错误,请稍后重试.',
            err
        });
    })
});

//外科治疗病例查看
router.get("/Medicallook/:id", (req, res) => {
    let id = req.params.id
    if (!id) {
        return res.json({
            code: 201,
            mes: "缺少必要参数"
        })
    }
    Medicalinfor.findOne({ id: id, savetime: moment().format('YYYY-MM-DD 00:00:00') }).then(data => {
        return res.json({
            code: 200,
            mes: "查询成功",
            data
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "查询错误",
            err
        })
    })
})



module.exports = router;
